package com.yupi.yuaiagent.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 联网搜索工具类
 */
public class WebSearchTool {

    //SearchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    private final String apiKey;

    public WebSearchTool(String apiKey) {
        this.apiKey = apiKey;
    }

    @Tool(description = "Search for information form Baidu Search Engine")
    public String search(@ToolParam(description = "Search query keyword") String query) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", apiKey);
        paramMap.put("engine", "baidu");

        String response = HttpUtil.get(SEARCH_API_URL, paramMap);
        // 取出返回结果的前5条消息
        JSONObject jsonObject = JSONUtil.parseObj(response);
        JSONArray organicResults = jsonObject.getJSONArray("organic_results");
        // 修复：确保只获取数组中实际存在的元素，避免IndexOutOfBoundsException
        int endIndex = Math.min(organicResults.size(), 5);
        List<Object> objects = organicResults.subList(0, endIndex);
        //拼接搜索结果为字符串
        String result = objects.stream().map(item -> {
            JSONObject tempJSONObject = (JSONObject) item;
            return tempJSONObject.toString();
        }).collect(Collectors.joining(","));
        return result;
    }
}
